﻿using System;
using System.IO;
using System.Net;

namespace RedirectCacheTest {
    internal class Program {
        private static void Main(string[] args) {
            if (!HttpListener.IsSupported) {
                Console.WriteLine("HttpListener not supported");
                return;
            }
            var listener = new HttpListener();
            listener.Prefixes.Add("http://*:12345/");
            listener.Start();
            const string cookieKey = "Original";
            try {
                while (true) {
                    var ctx = listener.GetContext();
                    Console.WriteLine("Got request for {0}", ctx.Request.RawUrl);
                    using (var response = ctx.Response) {
                        if (ctx.Request.RawUrl == "/") {
                            using (var output = new StreamWriter(response.OutputStream)) {
                                output.WriteLine("<a href='/first'>First</a>");
                            }
                        } else if (ctx.Request.RawUrl == "/first") {
                            response.SetCookie(new Cookie(cookieKey, ctx.Request.RawUrl) {Expires = DateTime.Now.AddHours(1)});
                            response.StatusCode = 301;
                            response.RedirectLocation = "/second";
                        } else {
                            using (var output = new StreamWriter(response.OutputStream)) {
                                output.WriteLine(ctx.Request.Cookies[cookieKey]);
                                response.SetCookie(new Cookie(cookieKey, null) {Expires = new DateTime(1980, 1, 1)});
                            }
                        }
                    }
                }
            } finally {
                listener.Stop();
            }
        }
    }
}